import { _decorator, Color, Component, EventTouch, instantiate, Label, Node, Sprite, v2, Vec2 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('EditorShapData')
export class EditorShapData extends Component {
    @property(Node)
    buttons: Node = undefined

    @property(Node)
    buttonsChild: Node = undefined

    clickData: boolean[][] = []

    onLoad() {
        this.createButton()
        this.initData()
        this.registerEvent()
        this.clear()
    }
    createButton() {
        for (let i = 0; i < 16; i++) {
            const node = instantiate(this.buttonsChild)
            node.active = true
            node.parent = this.buttons
        }
    }

    initData() {
        for (let i = 0; i < 4; i++) {
            this.clickData[i] = []
            for (let j = 0; j < 4; j++) {
                this.clickData[i][j] = false
            }
        }
    }

    outData() {
        // log(this.clickData)
        const data: Vec2[] = []
        for (let i = 0; i < 4; i++) {
            for (let j = 0; j < 4; j++) {
                if (this.clickData[i][j]) {
                    data.push(v2(i, j))
                }
            }
        }
        // 做偏移后转字符串
        let str = ''
        data.forEach((v, index) => {
            const x = v.x - 1
            const y = v.y - 1
            str += `(${x}, ${y})`
            if (index !== data.length - 1) {
                str += ';'
            }
        })
        console.log(str)
    }

    clear() {
        this.buttons.children.forEach((node, index) => {
            node.getComponent(Sprite).color = new Color(220, 220, 220, 255)
            const pos = this.indexToRowCol(index)
            this.clickData[pos.x][pos.y] = false

            //标记中心点（0，0）
            if (index === 5) {
                node.getComponent(Sprite).color = new Color(165, 47, 85, 255)
                node.children[0].getComponent(Label).string = '(0,0)'
            }
        })
    }

    onButtonClick(index: number, node: Node) {
        //Green
        node.getComponent(Sprite).color = new Color(0, 255, 0, 255)

        const pos = this.indexToRowCol(index)
        this.clickData[pos.x][pos.y] = true
    }

    registerEvent() {
        this.buttons.children.forEach((node, index) => {
            node.on(Node.EventType.TOUCH_END, (event: EventTouch) => {
                this.onButtonClick(index, event.target)
            })
        })
    }

    /** 0-15 转化为数据坐标 */
    indexToRowCol(index: number) {
        const row = Math.floor(index / 4)
        const col = index % 4
        // warn(row, col)
        return v2(row, col)
    }
    onClickClose() {
        this.node.active = false
    }
}

